const mongoose = require('mongoose');
const Upload = require('../models/upload.models');
var multer  = require('multer')
var path = require('path');

exports.upload = function(req, res, next) {
  var storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, './uploads')
      },
      filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now()+path.extname(file.originalname))
      }
    })

  var upload = multer({ storage: storage }).single('avatar');
  
  upload(req, res, function (err) {
      if (err) {
        // An error occurred when uploading
        
        return
      }
      req.file.paths = req.body.paths;
    req.file.cateId = req.body.cateId;
      console.log(req.file)
      // Everything went fine
      const upload = new Upload(req.file);
          upload.save().then(data => {
              res.json(data);
          });
    })
};

exports.create = function (req,res,next) {
    const upload = new Upload(req.body);
    upload.save().then(data=>{
        res.json(data);
    });
};

exports.get = function (req,res,next) {
  const id = req.params.id;
  Upload.findById(id,function(err,result){
    res.json(result);
  })
};

exports.update = function (req,res,next) {
  const id = req.params.id;
  Upload.findByIdAndUpdate(id,{ $set:req.body },{ new:false }).then(data=>{
    res.json(data);//data:更新之前的数据
  })
};

exports.delete = function (req,res,next) {
  const id = req.params.id;
  Upload.findByIdAndRemove(id,function(err,doc){
    res.json({message:'数据删除成功',status:200});
  })
};

exports.removes = function (req, res, next) {
  const ids = req.body.ids.split(',');//将id拆分成数组
  if (ids.length > 0) {
    Upload.remove({ _id: { $in: ids } }).then(data => {
      res.json({ status: 200, message: '删除多条数据成功' });
    });
  }
}

exports.list = function (req,res,next) {
  console.log('body',req.body)
  var page = req.body.page ? req.body.page : 1;
  var rows = req.body.rows ? req.body.rows : 5;
  
  var quertCondition = {};

  if(req.body.cateId && req.body.cateId.trim().length > 0){
    quertCondition={
      paths: new RegExp(req.body.cateId,'g')
    };
  };
console.log(Upload)
Upload.paginate(quertCondition, { page: +page, limit: +rows }, function(err, result) {
    result.rows = result.docs;
    console.log(result)
    delete result.docs;
    res.json(result);
  });
};
